<?php
/**
 * Created by PhpStorm.
 * User: administrator
 * Date: 2016/9/26 0026
 * Time: 10:51
 */
namespace Home\Controller;
use Think\Controller;

//用户中心全局控制
class GenerateController extends  Controller{

    public function generateIdImg()
    {

        $order_id = trim(I('order_id'));//订单ID

        $order_entity = M('order_info')->where(array('order_id' => $order_id))->field('user_id,idcard,idcard_img,idcardanti_img,address_id,consignee')->find();


        //去身份证记录表查找是否接口有记录
        $card_record = M('card_record')->where(array('id_card' => $order_entity['id_card'], 'consignee' => $order_entity['consignee'], 'type' => 1))->find();



        //如果记录不为空则直接读取
        if (!empty($card_record)) {


            $address_data['idcard_img'] = $card_record['idcard_img'];
            $address_data['idcardanti_img'] = $card_record['idcardanti_img'];
            $address_data['card_record_id'] = $card_record['id'];
            $address_data['source'] = 1;

            $ad_where['address_id'] = $order_entity['address_id'];

            M('user_address')->where($ad_where)->save($address_data);

            $order_data['idcard_img'] = $card_record['idcard_img'];
            $order_data['idcardanti_img'] = $card_record['idcardanti_img'];


            $where['order_id'] = $order_id;

            M('order_info')->where($where)->save($order_data);

            echo json_encode(array("status" => 1, 'info' => '生成成功'));
            exit;

        } else {


            //如果记录为空则去请求API接口获取信息
            $json_string = _get_card_information($order_entity['consignee'], $order_entity['idcard']);//传入姓名和身份证



            $card_data = json_decode($json_string);//解析获取的json数据

            $ResponseCode = $card_data->ResponseCode;//判断是否请求成功

            $Result = $card_data->Identifier->Result;//数据是否一致

            //数据请求成功
            if ($ResponseCode == 100 && $Result == '一致') {

                $add_data['consignee'] = $order_entity['consignee'];
                $add_data['id_card'] = $order_entity['idcard'];
                $add_data['add_time'] = time();
                $add_data['user_id'] = $order_entity['user_id'];
                $add_data['type'] = 1;
                $card_record_id = M('card_record')->add($add_data);//新增身份证记录表记录

                $_SESSION['card_record_id'] = $card_record_id;//将身份证记录ID存入session

                $md5_ID = md5($card_data->Identifier->IDNumber . '951753');//通过身份证号码和随机数生成md5

                $image = $card_data->Identifier->Photo;//身份证头像的base64

                $img_decode = base64_decode(str_replace(" ", "+", $image));//把头像的base64中空格替换为+

                $img = imagecreatefromstring($img_decode);//通过文件流创建图片


                $dir_head = $_SERVER['DOCUMENT_ROOT'] . '/attas/cardsimg/heads/' . $card_record_id . '/';//检验存储头像用户ID文件夹是否存在
                //文件夹不存在则创建
                if (!is_readable($dir_head)) {
                    is_file($dir_head) or mkdir($dir_head, 0700);// 0777，意味着最大可能的访问权
                }



                $newFilePath = './attas/cardsimg/heads/' . $card_record_id . '/' . $md5_ID . '.jpg';//头像的保存路径和图片名字

                imagepng($img, $newFilePath);//保存图片到本地
                imagedestroy($img);//销毁文件流



                $head_img=$_SERVER['DOCUMENT_ROOT'] .'/attas/cardsimg/heads/' . $card_record_id . '/' . $md5_ID . '.jpg';


                if (!file_exists($head_img)) {
                    echo json_encode(array("status" => 0, 'info' => '身份证图片头像不存在'));
                    exit;
                }

                $name = $card_data->Identifier->Name;//姓名

                $Sex_two = $card_data->Identifier->Sex;//性别

                //mb_substr函数是作为截取
                $Sex = mb_substr($Sex_two, 0, 1, 'utf-8');

                $Birthday = $card_data->Identifier->Birthday;//生日

                $year = mb_substr($Birthday, 0, 4, 'utf-8');

                $month = mb_substr($Birthday, 5, 2, 'utf-8');

                $day = mb_substr($Birthday, 8, 2, 'utf-8');

                $Address = $card_data->Identifier->Address;//住址

                $address = mb_substr($Address, 0, 11, 'utf-8');

                $IDNumber = $card_data->Identifier->IDNumber;//身份证号码


                $NativePlace = $card_data->Identifier->NativePlace;//籍贯

                $beijing_str = strpos($NativePlace, '北京市');

                $shanghai_str = strpos($NativePlace, '上海市');


                if (($beijing_str !== false) || ($shanghai_str !== false)) {

                    $city = mb_substr($NativePlace, 0, 3, 'utf-8');
                    $area = mb_substr($NativePlace, 3, 6, 'utf-8');
                    $native_place = $city . '公安局' . $area . '分局';
                } else {
                    $str_count = $this->utf_8_length($NativePlace);//得到籍贯的长度

                    /*如果字符长度大于6则截取6位*/
                    if ($str_count > 6) {
                        $city = mb_substr($NativePlace, -3, 3, 'utf-8');
                    } else {
                        $city = mb_substr($NativePlace, 3, 6, 'utf-8');
                    }

                    $native_place = $city . '公安局';
                }


                $dir_card = $_SERVER['DOCUMENT_ROOT'] . '/attas/cardsimg/cards/' . $card_record_id . '/';//检验存储身份证用户ID文件夹是否存在

                //文件夹不存在则创建
                if (!is_readable($dir_card)) {
                    is_file($dir_card) or mkdir($dir_card, 0700);// 0777，意味着最大可能的访问权
                }


                $image = new \Think\Image();//调用think php添加水印函数

                /*
                 * open打开原图片
                 * text为文字水印
                 * water为图片水印
                 * save打好水印后保存的图片
                 * crop裁剪图片
                 * thumb_img 压缩图片
                 * */
                $image->open('./images/card.jpg')->text($name, './data/font/simhei.ttf', 14, '#000105', array(124, 59))->save('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg');

                $image->open('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg')->text($Sex, './data/font/simhei.ttf', 14, '#000105', array(124, 104))->save('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg');

                $image->open('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg')->text($year, './data/font/simhei.ttf', 14, '#000105', array(124, 149))->save('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg');

                $image->open('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg')->text($month, './data/font/simhei.ttf', 14, '#000105', array(214, 149))->save('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg');

                $image->open('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg')->text($day, './data/font/simhei.ttf', 14, '#000105', array(269, 149))->save('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg');

                $image->open('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg')->text($address, './data/font/simhei.ttf', 14, '#000105', array(124, 191))->save('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg');

                $image->open('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg')->text($IDNumber, './data/font/OCR-B_10_BT.ttf', 20, '#000000', array(212, 321))->save('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg');

                $image->open('./attas/cardsimg/heads/' . $card_record_id . '/' . $md5_ID . '.jpg')->thumb(178, 220, \Think\Image::IMAGE_THUMB_CENTER)->save('./attas/cardsimg/heads/' . $card_record_id . '/' . $md5_ID . '.jpg');

                $image->open('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg')->water('./attas/cardsimg/heads/' . $card_record_id . '/' . $md5_ID . '.jpg', array(370, 50))->save('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg');

                $image->open('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg')->text($native_place, './data/font/simhei.ttf', 14, '#000105', array(244, 641))->save('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '_big.jpg');

                $image->open('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '_big.jpg')->crop(599, 375)->save('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '_api.jpg');//API身份证正面原本

                $image->open('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '_big.jpg')->crop(599, 380, 0, 375)->save('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '_api_1.jpg');//API身份证反面原本

                $image->open('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '_big.jpg')->crop(599, 375)->save('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg');

                $image->open('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '_big.jpg')->crop(599, 380, 0, 375)->save('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '_1.jpg');

                $this->thumb_img('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg', 599, './attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '.jpg');

                $this->thumb_img('./attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '_1.jpg', 599, './attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '_1.jpg');


                $file = './attas/cardsimg/cards/' . $card_record_id . '/' . $md5_ID . '_big.jpg';//身份证大图路径

                $card_status = file_exists($file);  //检验身份证大图是否存在

                @unlink($file);//删除身份证大图

                if ($card_status == true) {
                    $card_1 = $card_record_id . '/' . $md5_ID . '.jpg';
                    $card_2 = $card_record_id . '/' . $md5_ID . '_1.jpg';


                    $address_data['idcard_img'] = $card_1;
                    $address_data['idcardanti_img'] = $card_2;
                    $address_data['card_record_id'] = $card_record_id;
                    $address_data['source'] = 1;


                    $ad_where['address_id'] = $order_entity['address_id'];

                    M('user_address')->where($ad_where)->save($address_data);

                    $order_data['idcard_img'] = $card_1;
                    $order_data['idcardanti_img'] = $card_2;


                    $where['order_id'] = $order_id;

                    M('order_info')->where($where)->save($order_data);


                    $save_data['idcard_img'] = $card_1;
                    $save_data['idcardanti_img'] = $card_2;

                    M('card_record')->where(array('id' => $card_record_id))->save($save_data);

                    echo json_encode(array("status" => 1, 'info' => '生成成功'));
                    exit;
                } else {
                    echo json_encode(array("status" => 0, 'info' => '生成失败'));
                    exit;
                }
            } elseif ($Result == '不一致') {
                echo json_encode(array("status" => 0, 'info' => '身份证号和姓名不匹配'));
                exit;
            } else {
                echo json_encode(array("status" => 0, 'info' => '身份证号码错误'));
                exit;
            }

        }
    }


    function utf_8_length($str)
    {
        if (empty($str)) {
            return 0;
        }
        if (function_exists('mb_strlen')) {
            return mb_strlen($str, 'utf-8');
        } else {
            preg_match_all("/./u", $str, $ar);
            return count($ar[0]);
        }
    }

    /*
    * $img_path 被压缩的图片的路径
    * $thumb_w 压缩的宽
    * $save_path 压缩后图片的存储路径
    */
    public function thumb_img($img_path, $thumb_w, $save_path)
    {
        $image = new \Think\Image();
        $image->open($img_path);
        $width = $image->width(); // 返回图片的宽度
        if ($width > $thumb_w) {
            $width = $width / $thumb_w; //取得图片的长宽比
            $height = $image->height();
            $thumb_h = ceil($height / $width);
        }
        $image->thumb($thumb_w, $thumb_h)->save($save_path);
    }
    
    
}